/**
 * GTURLComposer.n
 *
 * The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License 
 * at http://www.mozilla.org/MPL/
 * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
 * either express or implied. See the License for the specific language governing rights and limitations 
 * under the License.
 *
 * The Original Code is gcast-toolbox4iphone.
 *
 * The Initial Developers of the Original Code is Giannandrea Castaldi.
 */
#import "GTURLComposer.h"

@interface GTURLComposer ()
@property(nonatomic,retain,readwrite) NSString *stringBaseUrl;
@property(nonatomic,retain,readwrite) NSMutableDictionary *parameters;
- (NSString *)escapeForURL:(NSString *)value;
@end

@implementation GTURLComposer
@synthesize stringBaseUrl, parameters;

+ (id)composerWithStringBaseURL:(NSString*)aStringBaseUrl {
  return [[[GTURLComposer alloc] initWithStringBaseURL:aStringBaseUrl] autorelease];
}

- (id)initWithStringBaseURL:(NSString*)aStringBaseUrl {
  if ((self = [super init])) {
    self.stringBaseUrl = aStringBaseUrl;
    self.parameters = [NSMutableDictionary dictionary];    
  }
  return self;
}

- (void)dealloc {
  [stringBaseUrl release];
  [parameters release];
  [super dealloc];
}

- (void)setParameter:(NSString *)aParameter toValue:(NSString *)aValue {
  [parameters setObject:aValue forKey:aParameter];
}

- (NSURL *)URL {
  NSURL *url;
  if ([self.parameters count] > 0) {
    NSMutableString *parametersAsString = [NSMutableString stringWithCapacity:0];
    BOOL first = TRUE;
    for (NSString *key in self.parameters) {
      if (first) {
        [parametersAsString appendString:[NSString stringWithFormat:@"%@=%@", [self escapeForURL:key], [self escapeForURL:[self.parameters objectForKey: key]]]];
        first = FALSE;
      }
      else {
        [parametersAsString appendString:[NSString stringWithFormat:@"&%@=%@", [self escapeForURL:key], [self escapeForURL:[self.parameters objectForKey: key]]]];
      }
    }
    url = [NSURL URLWithString:[NSString stringWithFormat: @"%@?%@", self.stringBaseUrl, parametersAsString]];
  }
  else {
    url = [NSURL URLWithString:self.stringBaseUrl];
  }
  return url;
}

- (NSString *)escapeForURL:(NSString *)value {
  NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                         (CFStringRef)value,
                                                                         NULL,
                                                                         CFSTR("!*'();:@&=+$,/?%#[]"),
                                                                         kCFStringEncodingUTF8);
  [result autorelease];
	return result;
}


@end
